<template>
    <div>
        <el-form
            :model="settlementForm"
            ref="form"
            label-width="144px"
            class="ccui-form"
            :rules="rules"
        >
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="填报单位：" prop="reportInOrgName">
                        <el-select
                            v-model="settlementForm.reportInOrgName"
                            placeholder="请选择填报单位"
                            @change="changeReportInOrgId"
                        >
                            <el-option
                                v-for="item in reportOptions"
                                :key="item.orgId"
                                :label="item.name"
                                :value="item.name"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                
                <el-col :span="12">
                    <el-form-item label="结算期间：" prop="settlementStart">
                        <el-date-picker
                            class="dateClass"
                            v-model="settlementForm.settlementStart"
                            type="date"
                            placeholder="开始日期"
                            :picker-options="pickerOptions1"
                            @change="handleDate"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                        >
                        </el-date-picker>
                        &nbsp; 至
                        <el-date-picker
                            class="dateClass"
                            v-model="settlementForm.settlementEnd"
                            type="date"
                            placeholder="结束日期"
                            :picker-options="pickerOptions2"
                            @change="handleDate1"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="结算单名称：" prop="settlementName">
                        <el-input
                            v-model="settlementForm.settlementName"
                            @blur="handleTrim('settlementName')"
                            placeholder="请输入结算单名称"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结算单编号：" prop="settlementCode">
                        <el-input v-model="settlementForm.settlementCode" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="合同编号：" prop="contractCode">
                        <el-input v-model="settlementForm.contractCode" disabled/>
                        <el-button
                            plain
                            type="single-number"
                            style="margin-left: 10px"
                            @click="handleContract"
                        >选择
                        </el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="合同名称：" prop="contractName">
                        <el-input v-model="settlementForm.contractName" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="供应商：" prop="supplierName">
                        <el-input v-model="settlementForm.supplierName" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="合同金额：" prop="contractMoney">
                        <el-input v-model="settlementForm.contractMoney" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="结算数量：" prop="currSetCount">
                        <el-input v-model="settlementForm.currSetCount" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="结算金额：" prop="currSetMoney">
                        <el-input v-model="settlementForm.currSetMoney" disabled/>
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="12">
                    <el-form-item label="编制人：" prop="reportUsername">
                        <el-input v-model="settlementForm.reportUsername" disabled/>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="编制日期：" prop="reportTime">
                        <el-date-picker
                            v-model="settlementForm.reportTime"
                            type="date"
                            placeholder="选择日期"
                            value-format="yyyy-MM-dd"
                            disabled
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            
            <el-row :gutter="10">
                <el-col :span="18">
                    <el-form-item label="备注：" prop="remarks">
                        <el-input
                            type="textarea"
                            :rows="5"
                            maxlength="1000"
                            show-word-limit
                            placeholder="请输入备注"
                            v-model="settlementForm.remarks"
                        >
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <contractDialog
            ref="contractDialog"
            :dialog-data="dialogData"
            :table-data="dialogData.tableData"
            @handlePageChange="handlePageChange"
            @search="search"
            @reset="reset"
            @getDialogTableData="getDialogTableData"
        />
    </div>
</template>

<script>
import contractDialog from "@/basa/components/public_practice/contractDialog";
import {getUserInfo, getReportInOrgData} from "@/basa/api";
import {addUrlPerFix, generateUUID} from "@/basa/utils";
import {getEquipmnetInfoForSettlement, listSmpEquipmentForScPage} from "@/app/settlement-management/equipment/api";

export default {
    name: "basicInfo",
    props: {
        settlementForm: {
            type: Object,
            default: () => {}
        },
        settlementList: {
            type: Array,
            default: () => []
        },
        editContractId: Number
    },
    components: {contractDialog},
    data() {
        return {
            dialogData: {
                title: "合同查询",
                tableData: [],
                searchData: [
                    {
                        label: "合同编号",
                        models: "contractCode"
                    },
                    {
                        label: "供应商",
                        models: "partyBName"
                    },
                    {
                        label: "合同正式编号",
                        models: "formalContractCode"
                    },
                    {
                        label: "合同名称",
                        models: "contractName"
                    },
                ],
                tableTheadOptions: [
                    {label: "合同编号",prop: "contractCode",  width: "100"},
                    {label: "合同正式编号",prop: "formalContractCode",  width: "100"},
                    {label: "合同名称", prop: "contractName"},
                    {label: "签订单位", prop: "partyAName"},
                    {label: "供应商", prop: "partyBName"},
                    {label: "填报单位", prop: "reportInOrgName"},
                    {label: "生效日期", prop: "enabledDate"}
                ],
                pages: {
                    total: 0,
                    pageNo: 1,
                    pageSize: 10
                }
            },
            rules: {
                reportInOrgName: [
                    {required: true, message: "请输入填报单位", trigger: "change"}
                ],
                settlementStart: [
                    {required: true, message: "请输入结算期间", trigger: "change"}
                ],
                settlementName: [
                    {required: true, message: "请输入结算单名称", trigger: "blur"}
                ],
                contractCode: [
                    {required: true, message: "请选择合同", trigger: "change"}
                ],
                currentSettlePayAmtIncludeTax: [
                    {required: true, message: "请输入本期支付金额", trigger: "blur"},
                    {
                        pattern: /(^(\d{0,12})\.(\d{0,8})$)|(^\d{0,12}$)/,
                        message: "请输入正确的本期支付金额"
                    }
                ],
                paymentNum: [
                    {required: true, message: "请输入支付单编号", trigger: "change"}
                ]
            },
            reportOptions: [],
            dateBool: true
        }
    },
    computed: {
        pickerOptions1() {
            // let that = this;
            return {
                disabledDate: function (time) {
                    return time.getTime() > Date.now();
                }
            };
        },
        pickerOptions2() {
            let that = this;
            return {
                disabledDate: function (time) {
                    if (that.settlementForm.settlementStart == "") {
                        return time.getTime() > Date.now() < time.getTime();
                    } else {
                        return (
                            time.getTime() > Date.now() ||
                            time.getTime() <
                            new Date(that.settlementForm.settlementStart).getTime() -
                            24 * 60 * 60 * 1000
                        );
                    }
                }
            };
        }
    },
    watch: {
        editContractId: {
            handler(n) {
                if (n) this.getEditContract(n);
            },
            immediate: true
        }
    },
    created() {
        this.getUserInfo();
    },
    methods: {
        // 提交表单验证
        handleSubmit() {
            return new Promise((resolve, reject) => {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        resolve(this.settlementForm);
                    } else {
                        reject("a");
                    }
                });
            });
        },
        getDialogTableData(r) {
            this.settlementForm.contractId = r.id;
            this.settlementForm.contractCode = r.contractCode;
            this.settlementForm.contractName = r.contractName;
            this.settlementForm.supplierName = r.partyBName;
            this.settlementForm.contractMoney = (+r.initTotalContractPriceIncludeTax).toFixed(2);
            this.settlementForm.supplierId = r.partyBId;
            this.settlementForm.supplierCode = r.partyBExtOid;
            // // 获取合同数据
            this.getContract(r.id);
        },
        // 获取合同数据
        getContract(id) {
            if (!id) return this.$showErrorMessage("合同ID不能为空");
            getEquipmnetInfoForSettlement({concId: id}).then(res => {
                let result = res.data.data;
                let arr = ["1305", "1306", "1307", "1308", "1309", "990103"];
                let serveData = result.smpConcMatLessListBOS.filter(item => {
                        return arr.some(_item => item.thirdCategoriesOfCode.startsWith(_item));
                });
                serveData.forEach(_item => {
                    let uuid = generateUUID();
                    _item.unitPriceWithTax = "";
                    _item.materialCode = _item.materialsCode;
                    _item.materialName = _item.materialsName;
                    _item.materialState = _item.matDescribe;
                    _item.measureUnit = _item.currentMeasuringUnit;
                    _item.brand = _item.manufacturer;
                    _item.categoryCode = _item.thirdCategoriesOfCode;
                    _item.categoryName = _item.thirdCategoriesOfName;
                    _item.settlementCount = _item.residualSettlementNumber;
                    _item.isOtherCost = 0;
                    _item.isMerge = 0;
                    _item.isMainInventory = 0;
                    _item.isCategories = 1; // 自己使用， 用于区分运输类数据
                    _item.moneyWithTax = (+null).toFixed(2);
                    _item.moneyWithoutTax = null;
    
                    _item.materialFirstId = _item.firstId;
                    _item.materialId = _item.id;
    
                    _item.mergeUuid = uuid;
                });
                this.settlementForm.smpPcConcBO = result.smpPcConcBO;
                this.settlementForm.smpConcMatLessListBOS = result.smpConcMatLessListBOS;
                let isJudgement = {
                    isFloat : result.smpPcConcBO.isFloatContractPrice,
                    isMultiRate : result.smpPcConcBO.multiRateCode,
                    isTaxRatePercent : result.smpPcConcBO.taxRatePercent,
                    isTaxRate: result.smpPcConcBO.taxRate,
                    isTaxRateCode: result.smpPcConcBO.taxRateCode,
                    serveData: serveData,
                    concId: id,
                    isContractCode: result.smpPcConcBO.contractCode
                };
                this.$bus.$emit("getContract", isJudgement);
            });
        },
        // 编辑获取税率信息
        getEditContract(id) {
            getEquipmnetInfoForSettlement({concId: id}).then(res => {
                let result = res.data.data;
                this.settlementForm.smpPcConcBO = result.smpPcConcBO;
                this.settlementForm.contractMoney = this.settlementForm.contractMoney? (+this.settlementForm.contractMoney).toFixed(2) : "";
                this.settlementForm.smpConcMatLessListBOS = result.smpConcMatLessListBOS;
                let isJudgement = {
                    isFloat : result.smpPcConcBO.isFloatContractPrice,
                    isMultiRate : result.smpPcConcBO.multiRateCode,
                    isTaxRatePercent : result.smpPcConcBO.taxRatePercent,
                    isTaxRate: result.smpPcConcBO.taxRate,
                    isTaxRateCode: result.smpPcConcBO.taxRateCode,
                    concId: id
                };
                this.$bus.$emit("getEditContract", isJudgement);
            });
        },
        // 选择合同编号
        handleContract() {
            if (!this.settlementForm.reportInOrgId && !this.settlementForm.reportInOrgName) {
                return this.$showErrorMessage("请先选择填报单位");
            }
            this.$refs["contractDialog"].dialogVisible = true;
            this.getContractList();
        },
        // 获取合同编号数据
        getContractList(data) {
            let params = {
                ...data,
                reportOrgId: this.settlementForm.reportInOrgId,
                pageNo: this.dialogData.pages.pageNo,
                pageSize: this.dialogData.pages.pageSize
            };
            listSmpEquipmentForScPage(params).then(res => {
                let result = res.data.data;
                result.rows.map(item => item.enabledDate = item.enabledDate.substr(0,10));
                this.dialogData.tableData = result.rows;
                this.dialogData.pages.pageNo = result.pageNo;
                this.dialogData.pages.total = result.recordsTotal;
            });
        },
        // 分页 - 切换每页总条数 与 页数
        handlePageChange(val, type) {
            if (type === 'current') {
                this.dialogData.pages.pageNo = val;
                this.getContractList();
            } else if (type === 'size') {
                this.dialogData.pages.pageSize = val;
                this.getContractList();
            }
        },
        search(searchData) {
            this.getContractList(searchData);
        },
        // 分页重置
        reset() {
            this.dialogData.pages.pageNo= 1;
            this.dialogData.pages.pageSize= 10;
            this.getContractList();
        },
        // 去除结算单名称空格
        handleTrim(key) {
            if (!this.settlementForm[key] || this.settlementForm[key] == "") return;
            this.$set(
                this.settlementForm,
                key,
                this.settlementForm[key].replace(/(^\s*)|(\s*)$/g, "")
            );
        },
        // 结算期间处理 互相控制
        handleDate() {
            this.settlementForm.settlementEnd = "";
        },
        handleDate1() {
            this.dateBool = false;
        },
        // 填报单位更改时触发
        changeReportInOrgId(row) {
            // 根据具体需求在修改
            const tempObj = this.reportOptions.find(e => e.name === row);
            this.settlementForm.reportInOrgId = tempObj.orgId;
            this.settlementForm.reportInOrgName = tempObj.name;
            // 切换时,清空相应字段值
            if (this.settlementForm.contractCode != "") {
                let arr = [
                    "contractCode",
                    "contractName",
                    "supplierName",
                    "contractMoney"
                ];
                arr.forEach(e => {
                    this.settlementForm[e] = "";
                });
                this.$nextTick(() => {
                    this.settlementForm.clearValidate();
                });
            }
        },
        // 获取登录信息
        getUserInfo() {
            getUserInfo(
                addUrlPerFix(process.env.VUE_APP_BASEP_URL) + "/apis/basap/getUserInfo",{
                    isShowPageLoading: true
                }
            ).then(res => {
                this.settlementForm.reportUsername = res.data.data.userInfo.name;
                this.getReportInOrgData(res.data.data.userInfo.openId);
            });
        },
        // 填报信息
        getReportInOrgData(openId) {
            getReportInOrgData({openIds: [openId]}).then(res => {
                this.reportOptions = res.data.data[openId];
                this.settlementForm.reportInOrgName =
                    this.settlementForm.reportInOrgName || this.reportOptions[0].name;
                this.settlementForm.reportInOrgId =
                    this.settlementForm.reportInOrgId || this.reportOptions[0].orgId;
            });
        },
    },
}
</script>

<style scoped lang="scss">
/deep/ .el-input {
    width: 260px;
}

/deep/ .el-button--single-number {
    width: 46px;
    margin-left: 10px;
    padding: 0 9px;
}

/deep/ .ccui-pre-form-item {
    .el-form-item__label {
        line-height: 16px;
    }
}

/deep/ .dateClass {
    width: 119px !important;
}
</style>